package bian

import (
	"errors"
	"fmt"
	"gitee.com/jinmingzhi/block-chain-news/model"
	"github.com/antchfx/htmlquery"
	"go.uber.org/zap"
	"time"
)

const url = "https://www.binancezh.co/zh-CN/support/announcement"

type biAn struct {
	name       string
	newArticle string
	timer      time.Duration
}

func NewBiAn(t time.Duration) *biAn {
	return &biAn{
		name:       "币安",
		newArticle: "",
		timer:      t,
	}
}

func (b *biAn) Monitor(articleChan chan<- model.Msg) {
	b.newArticle, _ = getArticle()
	log.Info(fmt.Sprintf("%s: %s", b.name, b.newArticle))
	go func() {
		t := time.NewTicker(b.timer)
		for range t.C {
			str, err := getArticle()
			if err != nil {
				continue
			}
			if str != b.newArticle {
				b.newArticle = str
				articleChan <- model.Msg{OriginName: b.name, Text: str}
			}
		}
	}()
}

func getArticle() (s string, err error) {
	defer func() {
		if e := recover(); e != nil {
			err = errors.New(fmt.Sprintf("%v", e))
		}
	}()
	doc, err := htmlquery.LoadURL(url)
	if err != nil {
		log.Error("failed to load url", zap.String("url", url), zap.Error(err))
		return "", err
	}
	node := htmlquery.FindOne(doc, `//main/div/div[3]/div[1]/div[2]/div[2]/div/a[1]`)
	if err != nil {
		log.Error("failed to find one", zap.String("url", url), zap.Error(err))
		return "", err
	}
	return htmlquery.InnerText(node), nil
}
